<?php

namespace App\Services;
use App\Models\Crm_Report;
use App\Traits\External;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class ReportService
{
    public function reportList($params)
    {
        $result = Crm_Report::getFilter($params)->Nodel()->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,3);
        $list['list'] = $result;

        return $list;
    }

    public function reportStatusUpdate($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Report::find($id);
                $res->status = $params['status'];
                if(!$res->save()){
                    throw new \Exception("更新Crm_Report举报状态失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function reportStatusDel($params)
    {
        $ids = explode(',',$params['ids']);
        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Report::find($id);
                $res->is_del = 'Y';
                if(!$res->save()){
                    throw new \Exception("删除Crm_Report举报失败".$id);
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }
}
